package com.newlink.building.userinfo.fragment

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.ScaleAnimation
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
import ceneax.app.lib.qrscan.QRScan
import ceneax.app.lib.qrscan.arch.IScanCallback
import ceneax.app.lib.qrscan.bean.ParseResult
import ceneax.app.lib.qrscan.widget.MultiResultsView
import com.google.mlkit.vision.barcode.common.Barcode
import com.newlink.building.common_base.base.BaseFragment
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.RegexUtils
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.activity.Module_UserInfo_DeviceMacScanActivityNL.Companion.REQUEST_QR_PICK_IMAGE
import com.newlink.building.userinfo.databinding.FragmentQrcodeScanBinding

/**
 * Created by xiaodong on 2025/1/16.
 */
class Module_UserInfo_QrCodeScanFragment : BaseFragment(), IScanCallback {
    private var mQRScan: QRScan? = null
    private lateinit var mBinding: FragmentQrcodeScanBinding
    override fun attachLayoutRes(): View {
        mBinding = FragmentQrcodeScanBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initView(view: View) {
        mQRScan = QRScan.Builder(requireActivity())
            .setQRPreviewView(mBinding.qrPreviewView)
            .setBarcodeFormats(Barcode.FORMAT_QR_CODE)
            .setScanCallback(this)
            .build()

        scanAnimation(mBinding.captureScanLine)
        checkScanLightState()
        mBinding.scanLight.setOnClickListener {
            if (mQRScan!!.qrCamera.isTorchEnabled) {
                mQRScan!!.qrCamera.enableTorch(false)
                mBinding.scanLight.setImageResource(R.drawable.ceneax_app_lib_qrscan_icon_torch_disable)
            } else {
                mQRScan!!.qrCamera.enableTorch(true)
                mBinding.scanLight.setImageResource(R.drawable.ceneax_app_lib_qrscan_icon_torch_enable)
            }
        }

        mBinding.scanGallery.setOnClickListener {
//            pickImageFromGallery()
            startPickPhoto()
        }

    }

    override fun lazyLoad() {
    }

    private fun scanAnimation(view: View) {
        val animation = ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f)
        animation.repeatCount = -1
        animation.repeatMode = Animation.RESTART
        animation.interpolator = LinearInterpolator()
        animation.duration = 1200
        view.startAnimation(animation)
    }

    override fun onResult(bitmap: Bitmap, results: Array<out ParseResult>) {
        if (results.size == 1) {
            bitmap.recycle()
            finishWithResult(results[0])
            return
        }

        val parseResult = mutableListOf<ParseResult>()
        for (item in results) {
            if (RegexUtils.checkMac(item.content)) {
                parseResult.add(item)
            }
        }
        if (parseResult.isNotEmpty() && parseResult.size == 1) {
            bitmap.recycle()
            finishWithResult(parseResult[0])
            return
        }
        val drawView = MultiResultsView(requireContext(), bitmap, *parseResult.toTypedArray())
        drawView.setBackgroundColor(Color.BLACK)
        drawView.tag = "multi_results_container"
        drawView.setOnSelectedListener { result: ParseResult? ->
            result?.let {
                bitmap.recycle()
                this.finishWithResult(result)
            }
        }
        mBinding.captureContainter.addView(drawView)

        mQRScan!!.qrCamera.unBindAll()
    }

    private fun startPickPhoto() {
        val pickIntent = Intent(Intent.ACTION_PICK)
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        requireActivity().startActivityForResult(pickIntent, REQUEST_QR_PICK_IMAGE)
    }

    private fun finishWithResult(result: ParseResult) {
        NLog.e("QrCodeScanFragment 扫码信息为:${result.content}")
        val activity = requireActivity()
        val bundle = Bundle()
        bundle.putString("data", result.content)
        bundle.putInt("type", 0)
        activity.setResult(RESULT_OK, activity.intent.putExtras(bundle))
        activity.finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        mQRScan!!.release()
    }

    override fun onResume() {
        super.onResume()
        scanAnimation(mBinding.captureScanLine)
        mQRScan?.qrCamera?.bindAll()
        checkScanLightState()
    }

    override fun onPause() {
        super.onPause()
        mQRScan?.qrCamera?.unBindAll()
    }

    private fun checkScanLightState() {
        mQRScan?.qrCamera?.let {
            if (it.preview != null) {
                mBinding.scanLight.setImageResource(if (it.isTorchEnabled) R.drawable.scan_light else R.drawable.ceneax_app_lib_qrscan_icon_torch_disable)
            }
        }
    }
}